/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.heathrow.daoImpl2;

import cz.muni.fi.heathrow.dao.StewardDAO;
import cz.muni.fi.heathrow.entities.Steward;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Martin Zitnik
 */
@Repository
public class StewardDAOImpl implements StewardDAO
{

    @PersistenceContext
    private EntityManager manager;

    public StewardDAOImpl()
    {
    }

    @Override
    public Steward get(Long id)
    {
        if (id == null)
            throw new IllegalArgumentException("id is null");

        return manager.find(Steward.class, id);
    }

    @Override
    public void create(Steward steward)
    {
        if (steward == null)
            throw new IllegalArgumentException("steward is null");
        if (steward.getId() != null)
            throw new IllegalArgumentException("steward id is not null");

        manager.persist(steward);
    }

    @Override
    public void update(Steward steward)
    {
        if (steward == null)
            throw new IllegalArgumentException("steward is null");
        if (steward.getId() == null)
            throw new IllegalArgumentException("steward id is null");

        manager.merge(steward);
    }

    @Override
    public void remove(Steward steward)
    {
        if (steward == null)
            throw new IllegalArgumentException("steward is null");
        if (steward.getId() == null)
            throw new IllegalArgumentException("steward id is null");

        manager.remove(steward);

    }

    @Override
    public List<Steward> findAll()
    {
        return manager.createQuery("FROM Steward").getResultList();
    }

    @Override
    public Steward findByPersonalId(Long personalId)
    {
        if (personalId == null)
            throw new IllegalArgumentException("personalId is null");

        TypedQuery<Steward> q = manager.createQuery("SELECT s FROM Steward AS s WHERE s.personalId = :personalId", Steward.class);
        q.setParameter("personalId", personalId);
        return q.getSingleResult();
    }

    @Override
    public List<Steward> findByAnyName(String anyName, int limit)
    {
        if (anyName == null)
            throw new IllegalArgumentException("anyName is null");

        return manager.createQuery("SELECT s FROM Steward AS s WHERE s.firstName LIKE :firstName OR s.lastName LIKE :lastName ORDER BY s.lastName")
                .setParameter("firstName", anyName + "%").setParameter("lastName", anyName + "%").setMaxResults(limit)
                .getResultList();
    }
}